layui.use(['layer', 'form', 'flow', 'util', 'element', 'carousel', 'laypage'], function () {
    var layer = layui.layer
        , form = layui.form
        , flow = layui.flow;
    var element = layui.element;
    var util = layui.util;
    var carousel = layui.carousel;//图片轮播组件
    var laypage = layui.laypage;
    var Games = {"gId": 0};
    var listsize = 0;//游戏总数

        var loginId_p=$.cookie('loginId');//获取cookie
        if (loginId_p==null||loginId_p=='null'){//判断是否登陆 =null=没登陆
            layer.msg("您还未登录");
        }else if(atob(loginId_p).indexOf("Logined:")==0){//登陆状态中
            $('#loginTag').text(utf8to16(atob(loginId_p)).substring(8,utf8to16(atob(loginId_p)).length));//解密字符串获取用户名
            $('#loginTag').after('<dl class="layui-nav-child">\n' +
                '                    <dd><a href="javascript:void(0)"  id="user_info_btn">个人资料</a></dd>\n' +
                '                    <dd><a href="javascript:void(0)" lay-active="e5" >修改密码</a></dd>\n' +
                '                </dl>');//添加个人资料选项卡
            $('#loginTag').attr("lay-active",null);
            $('#user_info_btn').attr("lay-active","e4");
            $('#exit_flag').after('\n' +
                '            <li class="layui-nav-item"><a href="javascript:void(0)" id="logout">退出登陆</a></li>');
            $('#logout').click(function () {
                $.cookie('loginId',null);
                window.location.replace("/games_info_sys");
            });
        }

    //建造实例
    carousel.render({
        elem: '#test1'
        ,width: '100%' //设置容器宽度
        ,height:'100%'
        ,anim:'fade'
    });

    //获取不重复随机数
    function getRandom(lengths) {
        var arr = [];//存放随机数的数组
        var arrLen = lengths;//用来限制范围
        for (var i = 0; i < 4; i++) {
            var radomNum = parseInt(Math.random() * arrLen);//生成范围内的数据数
            if (arr.indexOf(radomNum) == -1 && radomNum != 0) {
                //indexOf返回值为-1表示数组中没有和新随机数重复的值
                arr.push(radomNum);
            } else {
                //有重复值i--，不添加重复的值到数组中，并再循环一次
                i--;
            }
        }
        console.log(arr);
        return arr;
    }


    //获取游戏总数
    $.get("/games_info_sys/games/listCount.do", function (res) {
        listsize = res;
        //显示随机头部游戏
        var headGameId = getRandom(listsize);
        $("#head_game1").attr("gid", headGameId[0]);
        $("#head_game2").attr("gid", headGameId[1]);
        $("#head_game3").attr("gid", headGameId[2]);
        $("#head_game4").attr("gid", headGameId[3]);
        //第一个随机游戏信息
        $.get("/games_info_sys/games/selectOneGame.do?gId=" + headGameId[0], function (temp) {
            $("#head_gameImg1").attr("src", temp.gImagevo.url1);
            $("#head_gameTitle1").text(temp.gCnName);
        })
        $.get("/games_info_sys/games/selectOneGame.do?gId=" + headGameId[1], function (temp) {
            $("#head_gameImg2").attr("src", temp.gImagevo.url1);
            $("#head_gameTitle2").text(temp.gCnName);
        })
        $.get("/games_info_sys/games/selectOneGame.do?gId=" + headGameId[2], function (temp) {
            $("#head_gameImg3").attr("src", temp.gImagevo.url1);
            $("#head_gameTitle3").text(temp.gCnName);
        })
        $.get("/games_info_sys/games/selectOneGame.do?gId=" + headGameId[3], function (temp) {
            $("#head_gameImg4").attr("src", temp.gImagevo.url1);
            $("#head_gameTitle4").text(temp.gCnName);
        })


    })
    //获取文章总数
    $.get("/games_info_sys/info/selectListCount.do",function (res) {
        //分页组件
        laypage.render({
            elem: 'gameMsgListLimit'
            , count: res//数据总数，从服务端得到
            , theme: '#23262E'
            , limit:5
            , jump:function (obj,first) {
                $('#games_info_list').empty();//每切换一页之前清空之前的dom结构
                $.get("/games_info_sys/info/selectGamesInfoListLimit.do?page="+obj.curr,function (data) {
                    var infoList=data.data;
                    //遍历
                    layui.each(infoList, function (index, item){
                        //追加文章列表
                        $('#games_info_list').append('<div class="layui-card-body" id="info_list_solo">\n' +
                            '                  <div class="news-st">\n' +
                            '                    <a href="javascript:void(0)" lay-active="e2" infoId="'+item.infoId+'" title="'+item.infoTitle+'">\n' +
                            '                      <div class="game-info-title">'+item.infoTitle+'</div>\n' +
                            '                      <div class="games-info-content">'+cutString(item.infoContent,60)+'</div>\n' +
                            '                      <span class="games-info-time">'+item.infoTime+'</span>\n' +
                            '                    </a>\n' +
                            '                  </div>\n' +
                            '                </div>');
                    })
                })
            }
        })
    })

    //弹出登陆注册层宽高自适应函数
    function setpage() {
        if ($(window).width() < 458) {
            return ['100%', '100%'];
        } else {
            return ['25%'];
        }
    };
    //弹出信息层宽高自适应函数
    function setpageinfo() {
        if ($(window).width() < 458) {
            return ['100%', '100%'];
        } else {
            return ['70%', '70%'];
        }
    };

    //截取描述字符串,最多90字
    function cutString(str,num) {
        if (str.length > num) {
            var cutStr = str.substring(0, num) + '.........';
            return cutStr;
        } else {
            return str;
        }
    }

    //图片轮播
    carousel.render({
        elem: '#head'
        , interval: 10000
        , anim: 'fade'
        , height: '500px'
        , width: '100%'
    });

    //处理属性 为 lay-active 的所有元素事件,游戏列表的点击事件
    util.event('lay-active', {
        e1: function () {
            var gid = $(this).attr("gid");//获取自定义属性值:游戏id
            //弹出层,弹出详细信息
            layer.open({
                title: '游戏详情',
                type: 2,
                anim: 2,
                shadeClose: true, //点击遮罩关闭
                area: setpageinfo(),//调用函数判断宽度自适应
                content: '/games_info_sys/front_web/detail_game_page.html#/gid=' + gid
            });
        },
        e2:function () {
            var infoId=$(this).attr("infoId");//获取自定义属性值:文章id
            //弹出层,弹出文章详细信息
            layer.open({
                title: $(this).attr("title"),
                type: 2,
                anim: 2,
                shadeClose: true, //点击遮罩关闭
                area: setpageinfo(),//调用函数判断宽度自适应
                content: "/games_info_sys/front_web/detail_info_page.html#/infoId="+infoId
            });
        },
        e3:function () {
            //弹出层,弹出登陆注册页面
            layer.open({
                type: 1,
                title: false, //不显示标题栏
                anim: 2,
                shade: 0.8,
                closeBtn: 2,
                scrollbar:false,
                shadeClose: true, //点击遮罩关闭
                area: setpage(),//调用函数判断宽度自适应
                content:
                    '<div id="login"><!-- 登录注册切换动画 -->\n' +
                    '                <div id="status" style="bottom: 30px;">\n' +
                    '                    <i style="top: 0">登陆</i>\n' +
                    '                    <i style="top: 35px">注册</i>\n' +
                    '                    <i style="right: 5px">页</i>\n' +
                    '                </div>\n' +
                    '                <span style="top: 210px;">\n' +

                    '                        <p class="form"><input type="text" id="user" placeholder="请输入用户名"></p>\n' +
                    '                        <p class="form"><input type="password" id="passwd" placeholder="请输入密码"></p>\n' +
                    '                        <p class="form confirm"><input type="password" id="confirm-passwd" placeholder="请再次输入密码"></p>\n' +
                    '                        <input type="button" value="登陆" class="btn" id="login_btn" style="margin-right: 20px;">\n' +
                    '                        <input type="button" value="注册" class="btn" id="sign_btn" >\n' +

                    '                </span>\n' +
                    '            </div>\n',
                success:function (layero) {
                    //登陆页函数
                    var onoff = true;//根据此布尔值判断当前为注册状态还是登录状态
                    var confirm = layero.find(".confirm")[0];
                    //当注册按钮被点击
                    layero.find('#sign_btn').click(function () {
                        let status = layero.find("#status").find("i");
                        if (onoff) {
                            confirm.style.height = 51 + "px";
                            status[0].style.top = 35 + "px";
                            status[1].style.top = 0;
                            onoff = !onoff;
                        } else {
                            //注册代码
                            if(layero.find('#passwd').val()!=layero.find('#confirm-passwd').val()){
                                layer.msg("两次密码输入不一致!请重新输入");
                                layero.find('#passwd').val(null);
                                layero.find('#confirm-passwd').val(null);
                            }else {
                                var data={"uName":layero.find('#user').val(),"uPwd":layero.find('#passwd').val()};//将数据组装成JSON
                                $.post("/games_info_sys/publicUser/userReg.do",data,function (res) {//注册请求
                                    var msg=res.msg;
                                    layer.msg(msg);//显示回调信息
                                    if(msg=="注册成功"){//当注册成功时切换到登陆页面
                                        let status = layero.find("#status").find("i");
                                        confirm.style.height = 0;
                                        status[0].style.top = 0;
                                        status[1].style.top = 35 + "px";
                                        onoff = !onoff;
                                    }

                                })
                            }
                        }
                    });
                    //当登陆按钮被点击
                    layero.find('#login_btn').click(function() {
                        if (onoff) {
                            //登陆代码
                            var data={"uName":layero.find('#user').val(),"uPwd":layero.find('#passwd').val()};
                            $.post("/games_info_sys/publicUser/userLogin.do",data,function (res) {
                                var msg=res.msg;
                                layer.msg(msg);//显示回调信息
                                if (msg=="登陆成功"){
                                    loginId=res;//抛出登陆信息
                                    $.cookie('loginId',null);//清除原有cookie
                                    $.cookie('loginId',res.data);//写入用户名cookie记录已登录状态
                                    setTimeout(function () {
                                        layer.closeAll();
                                    },1000)
                                    setTimeout(function () {
                                        window.location.replace("/games_info_sys");
                                    },2000)

                                }
                            })
                        } else {
                            let status = layero.find("#status").find("i");
                            confirm.style.height = 0;
                            status[0].style.top = 0;
                            status[1].style.top = 35 + "px";
                            onoff = !onoff;
                        }
                    });

                }
            });
        },
        e4:function () {
            //弹出层,弹出用户信息
            layer.open({
                title: "个人资料",
                type: 2,
                anim: 2,
                shadeClose: true, //点击遮罩关闭
                area: ['51%','50%'],//调用函数判断宽度自适应
                content: "/games_info_sys/front_web/user_info.html"
            });
        },
        e5:function () {
            //弹出修改密码界面
            layer.open({
                type: 1,
                title: false, //不显示标题栏
                anim: 2,
                shade: 0.8,
                closeBtn: 2,
                shadeClose: true, //点击遮罩关闭
                area: setpage(),//调用函数判断宽度自适应
                content:'<div id="login">\n' +
                    '                <div id="status" style="width: 113px;">\n' +
                    '                   修改密码\n' +
                    '                </div>\n' +
                    '                <span>\n' +
                    '                    <form action="post">\n' +
                    '                        <p class="form"><input type="text" id="uName" placeholder="请确认您的用户名"></p>\n' +
                    '                        <p class="form"><input type="password" id="uPasswd" placeholder="请输入原密码密码"></p>\n' +
                    '                        <p class="form"><input type="password" id="new-passwd" placeholder="请输入新密码"></p>\n' +
                    '                        <input type="button" value="确认修改" id="update_btu" class="btn" style="margin-right: 20px;">\n' +
                    '                    </form>\n' +
                    '                </span>\n' +
                    '            </div>',
                success:function (layero) {
                    //当修改按钮被点击
                    layero.find('#update_btu').click(function() {
                        var data={uName:layero.find('#uName').val(),uPwd:layero.find('#uPasswd').val(),newUPwd:layero.find('#new-passwd').val()};
                        if(layero.find('#uName').val()==utf8to16(atob(loginId_p)).substring(8,utf8to16(atob(loginId_p)).length)) {//判断是否为当前用户
                            $.post("/games_info_sys/publicUser/updateUserPwd.do", data, function (res) {
                                if (res.msg == "修改成功") {
                                    layer.msg(res.msg);
                                    setTimeout(function () {
                                        //关闭当前层
                                        var index = parent.layer.getFrameIndex(window.name); //得到当前iframe层的索引
                                        parent.layer.close(index); //执行关闭
                                    }, 500);
                                    setTimeout(function () {
                                        //退出登陆
                                        $.cookie('loginId', null);
                                        window.location.replace("/games_info_sys");//导航到主页
                                    }, 500);
                                } else {
                                    layer.msg(res.msg);
                                }
                            })
                        }else {
                            layer.msg("输入用户名与当前账户用户名不匹配!");
                        }
                    })
                }
            });
        }
    });

    //编码转换utf8转utf-16
    function utf8to16(str) {
        var out, i, len, c;
        var char2, char3;

        out = "";
        len = str.length;
        i = 0;
        while(i < len) {
            c = str.charCodeAt(i++);
            switch(c >> 4) {
                case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
                    // 0xxxxxxx
                    out += str.charAt(i-1);
                    break;
                case 12: case 13:
                    // 110x xxxx   10xx xxxx
                    char2 = str.charCodeAt(i++);
                    out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
                    break;
                case 14:
                    // 1110 xxxx  10xx xxxx  10xx xxxx
                    char2 = str.charCodeAt(i++);
                    char3 = str.charCodeAt(i++);
                    out += String.fromCharCode(((c & 0x0F) << 12) |
                        ((char2 & 0x3F) << 6) |
                        ((char3 & 0x3F) << 0));
                    break;
            }
        }
        return out;
    }


    flow.load({
        elem: '#LAY_demo2' //流加载容器
        , scrollElem: '#LAY_demo2' //滚动条所在元素，一般不用填，此处只是演示需要。
        , isAuto: false
        , isLazyimg: true
        , done: function (page, next) { //加载下一页
            var lis = [];
            //以jQuery的Ajax请求为例，请求下一页数据（注意：page是从2开始返回）
            $.get('/games_info_sys/games/limit.do?page=' + page, function (res) {
                    //列表返回在data集合中
                    layui.each(res.data, function (index, item) {
                        var gImagevo = item.gImagevo;//接收预览图对象
                        lis.push('  <div class="layui-row layui-anim layui-anim-upbit">\n' +
                            '    <div class="layui-col-md12 game-lis">\n' +
                            '      <div class="layui-row grid-demo">\n' +
                            '        <div class="layui-col-md3">\n' +
                            '         <a href="javascript:void(0)" lay-active="e1" gid="' + item.gId + '" > <img class="cover-img" src="' + gImagevo.url0 + '">\n' +
                            '        </a> </div>\n' +
                            '        <div class="layui-col-md9">\n' +
                            '          <a href="javascript:void(0)" class="game-bt" lay-active="e1" gid="' + item.gId + '" >' + item.gCnName + '<span>（' + item.gEnName + '）</span></a>\n' +
                            '        </div>\n' +
                            '        <div class="layui-col-md9">\n' +
                            '          <ul class="game-info">\n' +
                            '            <li class="li">发售：' + item.gTime + '</li>\n' +
                            '            <li class="li">厂商：' + item.gMaker + '</li>\n' +
                            '            <li class="li">官网：<a href="' + item.gUrl + '" target="_blank" >点击进入</a> </li>\n' +
                            '            <li class="li">平台：' + item.gPlatform + '</li>\n' +
                            '            <li class="li">类型：' + item.gType + '</li>\n' +
                            '            <li class="li">语言：' + item.gLang + '</li>\n' +
                            '          </ul>\n' +
                            '        </div>\n' +
                            '        <div class="layui-col-md9">\n' +
                            '          <div class="game-miaoshu">' + cutString(item.gInfo,200) + '</div>\n' +
                            '        </div>\n' +
                            '      </div>\n' +
                            '    </div>\n' +
                            '</div>');
                    });
                    //执行下一页渲染，第二参数为：满足“加载更多”的条件，即后面仍有分页
                    //pages为Ajax返回的总页数，只有当前页小于总页数的情况下，才会继续出现加载更多
                    next(lis.join(''), page < res.count);
                }
            )
        }
    });

});